<template>
  <div>
    <!-- 表格列表 -->
    <div class="list">
      <!-- 订单总费用 -->
      <div class="header">
        <div class="header_left">
          <span class="line" />
          <span>订单总费用</span>
        </div>
        <div>
          ({{ ruleForm.startDate }}至{{ getCurrentYear }}- {{ getCurrentMonth }}-{{ getTime }})
        </div>
      </div>
      <el-table :data="orderTable">
        <el-table-column prop="id" label="顺序" />
        <el-table-column prop="name" label="项目名称" />
        <el-table-column prop="price" label="小计（元）" />
      </el-table>
      <!-- 入院费用核定 -->
      <div class="header">
        <div class="header_left">
          <span class="line" />
          <span>入院费用核定</span>
        </div>
        <div>
          ({{ ruleForm.startDate }}至{{ getCurrentYear }}- {{ getCurrentMonth }}-{{ getCheckTime }})
        </div>
      </div>
      <el-table :data="checkTable">
        <el-table-column prop="id" label="顺序" />
        <el-table-column prop="name" label="项目名称" />
        <el-table-column prop="price" label="小计（元）" />
      </el-table>
      <!-- 上传合同 -->
      <div class="header">
        <div class="header_left">
          <span class="line" />
          <span>上传合同</span>
        </div>
      </div>
      <!-- 图片上传 -->
      <el-upload
        :headers="headers"
        class="avatar-uploader"
        :action="BaseUrl + '/api/upload/add'"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <div class="uploadContent">
          <div class="btns">
            <el-button type="primary">上传图片</el-button>
            <el-button>下载预定协议</el-button>
          </div>
          <div>
            <img
              v-for="item in ruleForm.files"
              v-if="ruleForm.files"
              :src="imgUrl + item.file"
              alt=""
            />
          </div>
        </div>
      </el-upload>
      <!-- 按钮 -->
      <div class="buttons" style="text-align: center">
        <el-button type="primary" @click="lastStep">上一步</el-button>
        <el-button type="primary" @click="saveNo">保存暂不提交</el-button>
        <el-button type="primary" @click="saveSubmit">保存并提交</el-button>
        <el-button @click="back">返回</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, inject, defineEmits } from "vue";
import { useRouter } from "vue-router";
import { AddParams } from "@/api/market/hospitalized/type";
import { add as addData, update } from "@/api/market/hospitalized/hospitalized";
import { UploadProps } from "element-plus";
import { CompressImage } from "@/utils/imageUtils";

const router = useRouter();
const emit = defineEmits(["close"]);

//根路径
const BaseUrl = import.meta.env.VITE_APP_API_URL;
// 图片根路径
const imgUrl = ref(import.meta.env.VITE_IMG_URL);
const headers = { Authorization: localStorage.getItem("token") };

const ruleForm = inject<AddParams>("ruleForm")!;

//当前年
const getCurrentYear = computed(() => {
  return new Date(ruleForm.startDate).getFullYear();
});
//当前月份
const getCurrentMonth = computed(() => {
  return new Date(ruleForm.startDate).getMonth() + 1;
});

//总费用时间
const getTime = computed(() => {
  return new Date(ruleForm.startDate).getDate() + ruleForm.days!;
});

//入院核定时间
const getCheckTime = computed(() => {
  return new Date(ruleForm.startDate).getDate() + ruleForm.payDays!;
});

const allPrice = inject<any>("allPrice");
//下一步// 计算属性，用于动态生成 orderTable
const orderTable = computed(() => {
  const baseItems = [
    { id: 1, name: "床位费", price: allPrice.value.begPrice },
    { id: 2, name: "护理费", price: allPrice.value.servicePrice },
    { id: 3, name: "膳食费", price: allPrice.value.foodPrice },
    { id: 4, name: "押金", price: allPrice.value.cashPledge },
    { id: 5, name: "一次性生活费", price: allPrice.value.livingPrice },
  ];
  const total = baseItems.reduce((pre, item) => pre + item.price, 0);
  return [...baseItems, { name: "合计", price: total }];
});

// 计算属性，用于动态生成 orderTable
const checkTable = computed(() => {
  const baseItems = [
    { id: 1, name: "床位费", price: ruleForm.payDays! * ruleForm.begPrice! },
    { id: 2, name: "护理费", price: ruleForm.payDays! * ruleForm.servicePrice! },
    { id: 3, name: "膳食费", price: ruleForm.payDays! * ruleForm.foodPrice! },
    { id: 4, name: "押金", price: ruleForm.payDays! * ruleForm.cashPledge! },
    { id: 5, name: "一次性生活费", price: ruleForm.payDays! * ruleForm.livingPrice! },
  ];
  const total = baseItems.reduce((pre, item) => pre + item.price!, 0);
  return [...baseItems, { name: "合计", price: total }];
});

//文件上传前回调
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  let url = URL.createObjectURL(rawFile);
  return CompressImage(url, 80);
  // return true
};
//文件上传
const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  if (response.code == 10000) {
    console.log(response.data);
    ruleForm.files.push({ file: response.data.url });
  }
};

//上一步
const lastStep = () => {
  //改变步骤条状态
  //显示
  emit("close", true);
  // addShow.value = true;
};

//提交
const submit = async () => {
  await addData(ruleForm);
  router.push("/market/hospitalized");
  // console.log("res99", res);
};
//修改
const updateData = async () => {
  await update(ruleForm);
  router.push("/market/hospitalized");
};

//保存暂不提交
const saveNo = () => {
  ruleForm.state = 2;
  if (ruleForm.addTime) {
    //修改
    updateData();
  } else {
    //添加
    submit();
  }
};

//保存提交
const saveSubmit = () => {
  ruleForm.state = 1;
  if (ruleForm.addTime) {
    //修改
    updateData();
  } else {
    //添加
    submit();
  }
};
//返回
const back = () => {
  router.push("/market/hospitalized");
};
</script>

<style scoped>
.header {
  display: flex;
  align-items: center;
  height: 50px;
  margin-top: 40px;

  .header_left {
    display: flex;
    align-items: center;
    margin-right: 30px;
    font-weight: bold;

    .line {
      display: block;
      width: 6px;
      height: 20px;
      margin-right: 8px;
      background-color: #529bfd;
    }
  }
}

.list {
  padding-left: 60px;

  /deep/.cell {
    color: #000;
  }

  .uploadContent {
    display: flex;
    flex-direction: column;

    .btns {
      margin-bottom: 80px;
    }
  }
}
</style>
